package com.nhatth.contactsharer;

import java.util.Vector;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Checkable;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ContactSharerActivity extends ListActivity implements Runnable{
	/** Called when the activity is first created. */
	private Cursor mCursor;
	private ContactAdapter mAdapter;
	private ProgressDialog pd;
	ListView lv;
	View countLayout;
	static final String TAG = "ContactSharerActivity";
	Vector<Contact> checkedValue;
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Log.i(TAG, "ContactSharerActivity");
		
		//init cac bien
		mAdapter = new ContactAdapter(this, android.R.layout.simple_list_item_multiple_choice);
		
		//bind danh bạ vào ContactSharerActivity
		bindData(); 
		Log.i(TAG, "Cursor created!");
		
		//lấy list view để chỉnh tùy chọn
		lv = getListView();
		Log.i(TAG, "ListView got!");
		lv.setItemsCanFocus(false);
		lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); //Chọn nhiều
		countLayout = (View) findViewById(R.id.main_countLayout_lblCount); //Lấy cái label nhắc nhở
		countLayout.setBackgroundColor(Color.parseColor("#32000000"));
		
		//lấy EditText của txtSearch
		EditText txtSearch = (EditText) findViewById(R.id.main_txtSearch);
		int count = lv.getCheckItemIds().length;
		
		//lấy TextView lblCount
		TextView lblCount = (TextView) findViewById(R.id.main_countLayout_lblCount);
		lblCount.setText("Bạn đang chọn " + count + " số.");
		
		//Tìm kiếm
		txtSearch.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void afterTextChanged(Editable s) {
				Filter f = mAdapter.getFilter();
				f.filter(s.toString(), new Filter.FilterListener() {
					
					public void onFilterComplete(int count) {
						for (int i = 0; i < mAdapter.getCount(); i++) {
							lv.setItemChecked(i, false);
						}
						for (Contact con : checkedValue) {
							ContactAdapter fAdapter = (ContactAdapter) getListAdapter();
							Log.d(TAG, "mAdapter.getCount(): "+fAdapter.getCount());
							Log.d(TAG, "Contact name:"+con.name+":"+con.checked+":"+fAdapter.getPosition(con));
							lv.setItemChecked(fAdapter.getPosition(con),true);
						}
					}
				});
			}
		});
		checkedValue = new Vector<Contact>();
	}
	
	//Tạo ra menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	//Dùng để nhảy số khi chọn
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Contact con = (Contact)l.getItemAtPosition(position);
		if (!checkedValue.contains(con)) {
			con.checked = true;
			checkedValue.add(con);
		}
		else {
			con.checked = false;
			checkedValue.remove(con);
		}
		mAdapter.notifyDataSetChanged();
		int count = checkedValue.size();
		TextView lblCount = (TextView) findViewById(R.id.main_countLayout_lblCount);
		lblCount.setText("Bạn đang chọn " + count + " số.");
	}

	//Khi chọn option trong menu
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		//Gửi đi
		case R.id.contactSharerActivity_menu_send:
			Log.i(TAG, "Clicked on Menu!");
			if (checkedValue.isEmpty()) {
				Context ctx = getApplicationContext();
				CharSequence message = "Bạn chưa chọn số nào!";
				Toast.makeText(ctx, message, Toast.LENGTH_SHORT).show();
			} else {
				long[] idArray = new long[checkedValue.size()];
				int index = 0;
				for (Contact con : checkedValue) {
					idArray[index] = con._id;
					index++;
				}
				Intent i = new Intent(this, ComfirmActivity.class);
				i.putExtra("contacts_id", idArray);
				startActivity(i);
			}
			break;
		//Xóa hết
		case R.id.contactSharerActivity_menu_clearAll:
			for (int i = 0; i < mAdapter.getCount(); i++) {
				lv.setItemChecked(i, false);
			}
			checkedValue.clear();
			int count = checkedValue.size();
			TextView lblCount = (TextView) findViewById(R.id.main_countLayout_lblCount);
			lblCount.setText("Bạn đang chọn " + count + " số.");
			break;
		}
		return true;
	}
	
	

	private void bindData() {
		Log.d(TAG, "in bindData() method");
		Thread bindThread = new Thread(this, "bindThread");
		pd = ProgressDialog.show(this, "Please wait...", "Loading data from Contacts");
		bindThread.start();
	}

	public void run() {
		//Cursor đến db
		Log.d(TAG, "bindThread.run()");
		Cursor mCursor = getContentResolver().query(
				ContactsContract.Contacts.CONTENT_URI,//URI của Contact để kết nói tới db
				new String[] { Contacts._ID, Contacts.DISPLAY_NAME },//Lấy ID và Name
				Contacts.HAS_PHONE_NUMBER + "=1", null, Contacts.DISPLAY_NAME);//Có số điện thoại và ORDER BY tên
		startManagingCursor(mCursor); //Bắt đầu cho activity kiểm soát hoạt động của Cursor mCursor
		
		int displayName = mCursor.getColumnIndex(Contacts.DISPLAY_NAME);
		int id = mCursor.getColumnIndex(Contacts._ID);
		while(mCursor.moveToNext()){
			Contact con = new Contact(mCursor.getString(displayName), mCursor.getLong(id));
			mAdapter.add(con);
		}
		Log.d(TAG, "done loading data");
		handler.sendEmptyMessage(0);
	}
	
	private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
                pd.dismiss();
                setListAdapter(mAdapter);
                Log.d(TAG, "done binding data");
        }
	};
}